import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:flutter_pickers/time_picker/model/suffix.dart';
import 'package:get/get.dart';

import '../../../dd_core/dd_other.dart';
import '../../../r.dart';
import '../controllers/dd_personal_center_controller.dart';
import '../views/dd_view_background.dart';

class DDEditProfilePage extends StatefulWidget {
  const DDEditProfilePage({Key? key}) : super(key: key);

  @override
  State<DDEditProfilePage> createState() => _DDEditProfilePageState();
}

class _DDEditProfilePageState extends State<DDEditProfilePage> {
  DDPersonalCenterController _controller =
      Get.find<DDPersonalCenterController>();

  @override
  void initState() {
    super.initState();
    _controller.editNickName.value =
        _controller.authModel.value.userinfo?.nickname ?? '';
    _controller.editBirth.value =
        _controller.authModel.value.userinfo?.birthday ?? '';
    _controller.editCountry.value =
        _controller.authModel.value.userinfo?.country ?? '';
    _controller.editImageUrl.value =
        _controller.authModel.value.userinfo?.avatarUrl;
    _controller.control.text = _controller.editNickName.value;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DDPersonalCenterController>(
        init: _controller,
        initState: (state) {},
        dispose: (state) {},
        builder: (controller) {
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Color(0xFFE7F6FC),
              title: Center(
                child: Text('Edit Profile'),
              ),
              leading: IconButton(
                icon: Image.asset(R.assetsImagesHomeSecond1),
                onPressed: () {
                  Get.back();
                },
              ),
              actions: [
                Container(
                  height: 32,
                  width: 70,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Color(0xFF4C5961), // 边框颜色
                      width: 1.0, // 边框宽度
                    ),
                    borderRadius: BorderRadius.circular(4.0), // 边框圆角（可选）
                  ),
                  child: CupertinoButton(
                    color: Color(0xFF53BFD7),
                    borderRadius: BorderRadius.circular(4.0),
                    padding:
                        EdgeInsets.only(top: 0, bottom: 0, left: 10, right: 10),
                    onPressed: () {
                      _controller.postProfile();
                    },
                    child: Text(
                      'Post',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Color(0xFFFFFFFF),
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
              ],
            ),
            backgroundColor: Color(0xFFE7F6FC),
            body: Stack(children: [
              Positioned.fill(
                child: Image.asset(
                  R.assetsImagesPerson20,
                  fit: BoxFit.fill,
                ),
              ),
              SafeArea(
                top: false,
                child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).unfocus();
                  },
                  child: Align(
                    alignment: Alignment.topCenter,
                    child: Obx(
                      () => SingleChildScrollView(
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            children: [
                              SizedBox(
                                height: 73,
                              ),
                              GestureDetector(
                                onTap: () {
                                  showModalBottomSheet(
                                      backgroundColor: Colors.transparent,
                                      context: context,
                                      isDismissible: true,
                                      isScrollControlled: false,
                                      builder: (BuildContext context) {
                                        return Container(
                                          height: 220,
                                          width: Get.width,
                                          margin: EdgeInsets.only(bottom: 10),
                                          child: Column(
                                            children: [
                                              Container(
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(10)),
                                                ),
                                                child: Column(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment
                                                          .spaceAround,
                                                  children: [
                                                    Container(
                                                      width: Get.width,
                                                      child: DDSafeButton(
                                                        padding:
                                                            EdgeInsets.only(
                                                                top: 20,
                                                                bottom: 20),
                                                        child: Text(
                                                          "Open Album",
                                                          style: TextStyle(
                                                              fontSize: 16,
                                                              color:
                                                                  Colors.blue),
                                                        ),
                                                        onPressed: () {
                                                          Navigator.pop(
                                                              context);
                                                          _controller
                                                              .requestPhotosPermission(
                                                                  context);
                                                        },
                                                      ),
                                                    ),
                                                    Divider(
                                                      color: Colors.grey,
                                                      height: 1,
                                                    ),
                                                    Container(
                                                      width: Get.width,
                                                      child: DDSafeButton(
                                                        padding:
                                                            EdgeInsets.only(
                                                                top: 20,
                                                                bottom: 20),
                                                        child: Text(
                                                          "Open Camera",
                                                          style: TextStyle(
                                                              fontSize: 16,
                                                              color:
                                                                  Colors.blue),
                                                        ),
                                                        onPressed: () {
                                                          Navigator.pop(
                                                              context);
                                                          controller
                                                              .requestCameraPermission(
                                                                  context);
                                                        },
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Container(
                                                width: Get.width,
                                                margin: EdgeInsets.only(
                                                    top: 15, bottom: 15),
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(10)),
                                                ),
                                                child: DDSafeButton(
                                                  padding: EdgeInsets.only(
                                                      top: 15, bottom: 15),
                                                  child: Text(
                                                    "cancel",
                                                    style: TextStyle(
                                                        fontSize: 16,
                                                        color: Colors.blue),
                                                  ),
                                                  onPressed: () {
                                                    Navigator.pop(context);
                                                  },
                                                ),
                                              )
                                            ],
                                          ),
                                        );
                                      });
                                },
                                child: Stack(
                                  clipBehavior: Clip.none,
                                  children: [
                                    (_controller.editImageUrl.value
                                                .dd_isNotEmpty &&
                                            _controller.editImageUrl.value!
                                                .startsWith('http'))
                                        ? Stack(
                                            children: [

                                              ClipRRect(
                                                borderRadius: BorderRadius.circular(43),
                                                child:
                                                CachedNetworkImage(
                                                  width: 86,
                                                  height: 86,
                                                  imageUrl: _controller
                                                      .editImageUrl.value ??
                                                      '',
                                                  placeholder: (context, url) =>
                                                      Placeholder(),
                                                  errorWidget:
                                                      (context, url, error) =>
                                                      Placeholder(),
                                                ),
                                              ),
                                              Positioned(
                                                child: Container(
                                                  width: 88,
                                                  height: 88,
                                                  child: Image.asset(
                                                    R.assetsImagesPerson21,
                                                    fit: BoxFit.fill,
                                                    // fit: BoxFit.cover,
                                                  ),
                                                ),
                                              ),
                                            ],
                                          )
                                        : Stack(
                                            children: [
                                              ClipRRect(
                                                borderRadius:
                                                    BorderRadius.circular(44.0),
                                                child: Image.file(
                                                  File(_controller
                                                          .editImageUrl.value ??
                                                      ''),
                                                  width: 86,
                                                  height: 86,
                                                  fit: BoxFit.cover,
                                                ),
                                              ),
                                              Positioned(
                                                child: Container(
                                                  width: 88,
                                                  height: 88,
                                                  child: Image.asset(
                                                    R.assetsImagesPerson21,
                                                    fit: BoxFit.fill,
                                                    // fit: BoxFit.cover,
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                    Positioned(
                                      right: -5,
                                      bottom: -5,
                                      child:
                                          Image.asset(R.assetsImagesPerson13),
                                      //width: 30,
                                      //  height: 30,
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(
                                height: 30,
                              ),
                              ProfileStyle2MenuItem(
                                title: "Nick Name",
                                content: _controller.editNickName.value,
                                onTap: () {},
                                control: _controller.control,
                                focusNode: _controller.focusNode,
                              ),
                              SizedBox(
                                height: 14,
                              ),
                              ProfileStyle0MenuItem(
                                title: "Date of Birth",
                                content: _controller.editBirth.value,
                                onTap: () {
                                  final now = DateTime.now();
                                  DateTime selectDate = DateTime.parse(
                                      _controller.editBirth.value);
                                  Pickers.showDatePicker(context,
                                      mode: DateMode.YMD,
                                      selectDate: PDuration(
                                        year: selectDate.year,
                                        month: selectDate.month,
                                        day: selectDate.day,
                                      ),
                                      suffix: Suffix(
                                          years: " year",
                                          month: " month",
                                          days: " day"),
                                      pickerStyle: PickerStyle(
                                          cancelButton: Container(
                                            alignment: Alignment.center,
                                            padding: const EdgeInsets.only(
                                                left: 22, right: 12),
                                            child: Text('Cancel',
                                                style: TextStyle(
                                                    color: Theme.of(context)
                                                        .unselectedWidgetColor,
                                                    fontSize: 16.0)),
                                          ),
                                          commitButton: Container(
                                            alignment: Alignment.center,
                                            padding: const EdgeInsets.only(
                                                left: 22, right: 12),
                                            child: Text('OK',
                                                style: TextStyle(
                                                    color: Theme.of(context)
                                                        .unselectedWidgetColor,
                                                    fontSize: 16.0)),
                                          )),
                                      maxDate: PDuration(
                                          year: now.year - 18,
                                          month: now.month,
                                          day: now.day),
                                      onConfirm: (date) async {
                                    _controller.editBirth.value =
                                        '${date.year?.to2tring()}-${date.month?.to2tring()}-${date.day?.to2tring()}';
                                  });
                                },
                              ),
                              SizedBox(
                                height: 14,
                              ),
                              ProfileStyle1MenuItem(
                                title: "Country",
                                content: _controller.editCountry.value,
                                onTap: () {
                                  List<String> countrys = [
                                    "USA",
                                    "Japan",
                                    "Germany",
                                    "India",
                                    "UK",
                                    "France",
                                    "Italy",
                                    "Canada",
                                    "South Korea",
                                    "Russia",
                                    "Australia",
                                    "Spain",
                                    "Mexico",
                                    "Indonesia",
                                    "Netherlands",
                                    "Saudi Arabia",
                                    "Turkey",
                                    "Switzerland",
                                    "Argentina",
                                    "Sweden",
                                    "Poland",
                                    "Belgium",
                                    "Thailand",
                                    "Egypt",
                                    "Austria"
                                  ];
                                  Pickers.showSinglePicker(
                                    context,
                                    data: countrys,
                                    pickerStyle: PickerStyle(
                                        cancelButton: Container(
                                          alignment: Alignment.center,
                                          padding: const EdgeInsets.only(
                                              left: 22, right: 12),
                                          child: Text('Cancel',
                                              style: TextStyle(
                                                  color: Theme.of(context)
                                                      .unselectedWidgetColor,
                                                  fontSize: 16.0)),
                                        ),
                                        commitButton: Container(
                                          alignment: Alignment.center,
                                          padding: const EdgeInsets.only(
                                              left: 22, right: 12),
                                          child: Text('OK',
                                              style: TextStyle(
                                                  color: Theme.of(context)
                                                      .unselectedWidgetColor,
                                                  fontSize: 16.0)),
                                        )),
                                    onConfirm: (p, position) {
                                      _controller.editCountry.value =
                                          countrys[position];
                                    },
                                    onChanged: (p, position) {},
                                  );
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ]),
          );
        });
  }
}

class ProfileStyle0MenuItem extends StatelessWidget {
  final String title;
  final String content;
  final VoidCallback onTap;

  ProfileStyle0MenuItem({
    required this.title,
    required this.onTap,
    required this.content,
  });

  @override
  Widget build(BuildContext context) {
    return DDViewBackGround(
      margin: const EdgeInsets.only(top: 10, bottom: 10, left: 32, right: 32),
      content: ListTile(
        leading: Text(
          title,
          style: TextStyle(fontSize: 12, color: Color(0x4D000000)),
        ),
        title: SizedBox(),
        trailing: Text(
          content,
          style: TextStyle(fontSize: 16, color: Color(0xFF404040)),
        ),
        onTap: onTap,
      ),
    );
  }
}

class ProfileStyle1MenuItem extends StatelessWidget {
  final String title;
  final String content;
  final VoidCallback onTap;

  ProfileStyle1MenuItem({
    required this.title,
    required this.onTap,
    required this.content,
  });

  @override
  Widget build(BuildContext context) {
    return DDViewBackGround(
      margin: const EdgeInsets.only(top: 10, bottom: 10, left: 32, right: 32),
      content: ListTile(
        leading: Text(
          title,
          style: TextStyle(fontSize: 12, color: Color(0x4D000000)),
        ),
        trailing: Container(
          constraints: BoxConstraints(maxWidth: 150),
          child: Row(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              SizedBox(
                width: 10,
              ),
              Text(
                content,
                style: TextStyle(fontSize: 16, color: Color(0xFF404040)),
              ),
              Icon(
                Icons.arrow_forward_ios,
                color: Color(0x80000000),
                size: 20,
              ),
            ],
          ),
        ),
        onTap: onTap,
      ),
    );
  }
}

class ProfileStyle2MenuItem extends StatelessWidget {
  final String title;
  final String content;
  final VoidCallback onTap;
  final TextEditingController control;
  final FocusNode focusNode;

  ProfileStyle2MenuItem({
    required this.title,
    required this.onTap,
    required this.content,
    required this.control,
    required this.focusNode,
  });

  @override
  Widget build(BuildContext context) {
    return DDViewBackGround(
      margin: const EdgeInsets.only(top: 10, bottom: 10, left: 32, right: 32),
      content: ListTile(
        leading: Text(
          title,
          style: TextStyle(fontSize: 12, color: Color(0x4D000000)),
        ),
        title: SizedBox(),
        trailing: SizedBox(
          width: 140,
          child: TextField(
            controller: control,
            textAlign: TextAlign.end,
            focusNode: focusNode,
            maxLength: 20,
            showCursor: false,
            keyboardType: TextInputType.text,
            style: TextStyle(
              color: Color(0xFF404040),
              //: FontWeight.bold,
              fontSize: 16,
              //letterSpacing: 36,
            ),
            decoration: InputDecoration(
                hintText: "",
                counterText: '',
                border: InputBorder.none,
                contentPadding: EdgeInsets.only(left: 30)),
          ),
        ),
        onTap: onTap,
      ),
    );
  }
}
